import $service from '../../../../service.js';
var util = require('../../../../utils/util.js')
import * as echarts from '../../../../common/ec-canvas/echarts';
var id; //作废id
var delnum; //删除类型  6处方 7检验检查 8健康指导 9住院建议
var doctor_id;
var numdata = [];
var timedata = [];
var page = 0; //页数
var that;
var queryzt = '';
var startTime;
var endTime;
const app = getApp();
let name = [];
let getListData = [
    'getUserRecords',
    'getOpenPrescriptions',
    'getInquiryInspectionOpinionList',
    'getHealthGuidanceList',
    'getHospitalizationList',
    'getPharmacistFeedbackList',
    'getApplicationFormList'
];
Page({
    data: {
        hospitalType: $service.hospitalType,
        istab: 1,
        isactive: '0',
        inquiryLogList: [], // 用户病例
        prescriptionlist: [], // 处方历史
        checklistList: [], // 检查检验意见单
        guidanceList: [], // 健康指导意见单
        hospitalizationList: [], // 住院建议
        pharmacistFeedbackList: [], //药师审方
        applicationFormList: [], // 申请单
        doctorInfo: {},
        startdate: '请选择开始时间',
        enddate: '请选择结束时间',
        starttime: '2000-01-01',
        endtime: '',
        isshow: false,
        prescription_type: '请选择',
        zt: '请选择',
        patient_phone: '',
        patient_name: '',
        isprescriptiontypeshow: false,
        isztshow: false,
        isdeleteshow: false, //作废弹窗
        reasons_invalidation: '', //作废理由
        name: '',
        ec: {
            onInit: initChart
        },
        loadingText: '',
        loadingType: true,
        year: 0,
        month: 0,
        date: ['日', '一', '二', '三', '四', '五', '六'],
        dateArr: [],
        isToday: [],
        workDate: [], // 医生排班数据
        isTodayWeek: false,
        todayIndex: 0,
        state: '',
        useFrom:"", //用户来源
        type: '',
        params: {
            "current": 1,
            "size": 10,
            "startDate": "",
            "endDate": "",
            "patientName": "",
            "patientPhone": "",
            "prescriptionState": "",
            "prescriptionType": "",
        },
        typeList: [{
            type: '中药',
            value: '1'
        }, {
            type: '西药',
            value: '2'
        }],
        stateList: [{
            state: '审核通过',
            value: '1'
        }, {
            state: '审核驳回',
            value: '2'
        }, {
            state: '审核中',
            value: '3'
        }],
        useFromList: [{
            useFrom: '审核通过',
            value: '1'
        }, {
            useFrom: '审核驳回',
            value: '2'
        }, {
            useFrom: '审核中',
            value: '3'
        }],
    },
    onLoad(e) {
        that = this.data;
        doctor_id = $service.getUserLocalStorage().doctor_id;
        if (e.num == 1) {
            this.data.istab = 3
        } else if (e.num == 2) {
            this.data.istab = 2;
            this.data.isactive = 0;
        }
        let now = new Date();
        let year = now.getFullYear();
        let month = now.getMonth() + 1;
        this.setData({
            year: year,
            month: month,
            isToday: '' + year + month + now.getDate(),
            istab: this.data.istab,
            isactive: this.data.isactive
        })
        this.dateInit();
        this.queryHistoryInterrogation()
    },
    dateInit: function (setYear, setMonth) {
        //全部时间的月份都是按0~11基准，显示月份才+1
        let dateArr = []; //需要遍历的日历数组数据
        let arrLen = 0; //dateArr的数组长度
        let now = setYear ? new Date(setYear, setMonth) : new Date();
        let year = setYear || now.getFullYear();
        let nextYear = 0;
        let month = setMonth || now.getMonth(); //没有+1方便后面计算当月总天数
        let nextMonth = (month + 1) > 11 ? 1 : (month + 1);
        let startWeek = new Date((month + 1) + '/' + 1 + '/' + year).getDay(); //目标月1号对应的星期
        let dayNums = new Date(year, nextMonth, 0).getDate(); //获取目标月有多少天
        let obj = {};
        let num = 0;
        if (month + 1 > 11) {
            nextYear = year + 1;
            dayNums = new Date(nextYear, nextMonth, 0).getDate();
        }
        arrLen = startWeek + dayNums;
        for (let i = 0; i < arrLen; i++) {
            if (i >= startWeek) {
                num = i - startWeek + 1;
                obj = {
                    isToday: '' + year + $service.addZero((month + 1)) + $service.addZero(num),
                    dateNum: num,
                    weight: 5
                }
            } else {
                obj = {};
            }
            dateArr[i] = obj;
        }
        this.setData({
            dateArr: dateArr
        })
        let nowDate = new Date();
        let nowYear = nowDate.getFullYear();
        let nowMonth = nowDate.getMonth() + 1;
        let nowWeek = nowDate.getDay();
        let getYear = setYear || nowYear;
        let getMonth = setMonth >= 0 ? (setMonth + 1) : nowMonth;
        if (nowYear == getYear && nowMonth == getMonth) {
            this.setData({
                isTodayWeek: true,
                todayIndex: nowWeek
            })
        } else {
            this.setData({
                isTodayWeek: false,
                todayIndex: -1
            })
        }
        this.getDoctorSchedulingListPc() //排班
    },



    onShow() {
        that = this.data;
        // doctor_id = $service.getUserLocalStorage().doctor_id;
        var time = util.formatTime(new Date());
        this.setData({
            doctorInfo: JSON.parse($service.getStore('doctorInfo')),
            endtime: time
        })
        // this.doctorSide_personal_inquiry_getWaitingInquirydata()
        this.getList();
    },
    onPullDownRefresh() {
        this.setData({
            loadingText: '加载更多',
            params: {
                "current": 1,
                "size": 10,
                "startDate": "",
                "endDate": "",
                "patientName": "",
                "patientPhone": "",
                "prescriptionState": "",
                "prescriptionType": "",
            }
        })
        this.getList();
        wx.stopPullDownRefresh()
    },
    onReachBottom: function () {
        if (that.loadingType == true) {
            that.params.current++
            this.setData({
                'params.current': that.params.current
            })
            this.getList();
        } else {
            this.setData({
                loadingText: '没有更多了'
            })
        }
    },
    loading() {
        if (that.loadingType == true) {
            that.params.current++
            this.setData({
                'params.current': that.params.current
            })
            this.getList();
        } else {
            this.setData({
                loadingText: '没有更多了'
            })
        }
    },
    // 问诊统计
    queryHistoryInterrogation() {
        app.http.queryHistoryInterrogation({
            statisticscode: '1'
        }).then(res => {
            let newTimeList = res.data.interrogation;
            numdata = [];
            timedata = [];
            for (var i = 0; i < newTimeList.length; i++) {
                numdata.unshift(newTimeList[i].number);
                timedata.unshift(newTimeList[i].datatime);
            }
            console.log(numdata, timedata)
        }).catch(err => {
            $service.showToast(err.msg);
        })
    },
    // 值班安排
    getDoctorSchedulingListPc() {
        let month = this.data.month >= 10 ? this.data.month : ("0" + this.data.month)
        let params = {
            "doctorId": JSON.parse($service.getStore('userInfo')).id,
            "schedulingDate": this.data.year + '-' + month
        }
        app.http.getDoctorSchedulingListPc(params).then(res => {
            var timeList = res.data.list;
            for (var i = 0; i < timeList.length; i++) {
                timeList[i].day = this.getDay('day', timeList[i].schedulingDate);
                timeList[i].date = this.getDay('date', timeList[i].schedulingDate);
                for (var z = 0; z < this.data.dateArr.length; z++) {
                    if (timeList[i].isMorning == "1" || timeList[i].isAfternoon == "1" || timeList[i].isNight == "1") {
                        timeList[i].timeStr = $service.nothinglrsj(timeList[i].schedulingDate)
                        if (timeList[i].timeStr == this.data.dateArr[z].isToday) {
                            this.data.dateArr[z].timeshow = "1";
                        }
                    }
                }
            }
            this.setData({
                workDate: res.data.list,
                dateArr: this.data.dateArr
            })
        }).catch(err => {
            $service.showToast(err.msg);
        })
    },
    // 获取病例管理
    getList() {
        app.http[getListData[that.isactive]](that.params).then(res => {
            let data = res.data.list
            if (that.params.current == 1) {
                that.loadingText = '';
                name = data;
            } else {
                if (data.length <= 0) {
                    that.loadingType = false;
                    that.loadingText = '没有更多了';
                } else {
                    for (var i = 0; i < data.length; i++) {
                        name.push(data[i]);
                        that.loadingText = '加载更多';
                    }
                }
            }
            switch (that.isactive) {
                case '0':
                    that.inquiryLogList = name
                    break;
                case '1':
                    that.prescriptionlist = name
                    break;
                case '2':
                    that.checklistList = name
                    break;
                case '3':
                    that.guidanceList = name
                    break;
                case '4':
                    that.hospitalizationList = name
                    break;
                case '5':
                    that.pharmacistFeedbackList = name
                    break;
                case '6':
                    that.applicationFormList = name
                    break;
            }
            this.setData({
                inquiryLogList: that.inquiryLogList,
                prescriptionlist: that.prescriptionlist,
                checklistList: that.checklistList,
                guidanceList: that.guidanceList,
                hospitalizationList: that.hospitalizationList,
                pharmacistFeedbackList: that.pharmacistFeedbackList,
                applicationFormList: that.applicationFormList,
                loadingText: that.loadingText,
                loadingType: that.loadingType
            })
        }).catch(err => {
            $service.showToast(err.msg)
        })
    },

    //时间
    bindDateChange: function (e) {
        console.log('picker发送选择改变，携带值为', e.detail.value)
        var index = e.currentTarget.dataset.index;
        if (index == 1) {
            this.data.startdate = e.detail.value;
            startTime = this.data.startdate
        } else {
            this.data.enddate = e.detail.value;
            endTime = this.data.enddate
        }
        this.setData({
            startdate: this.data.startdate,
            enddate: this.data.enddate
        })
    },
    //输入框 
    inputChange(e) {
        var index = e.currentTarget.dataset.index;
        if (index == 0) {
            this.data.params.patientName = e.detail.value
        } else if (index == 1) {
            this.data.params.patientPhone = e.detail.value
        } else if (index == 2) {
            this.data.reasons_invalidation = e.detail.value
        }

        this.setData({
            'params.patientName': this.data.params.patientName,
            'params.patientPhone': this.data.params.patientPhone,
            reasons_invalidation: this.data.reasons_invalidation
        })
    },
    // 选择框
    pickChange(e) {
        let index = e.detail.value;
        let type = e.target.dataset.type;
        if (type === 'state') {
            that.params.prescriptionState = that.stateList[index].value;
            that.state = that.stateList[index].state;
        } else if (type === 'type'){
            that.params.prescriptionType = that.typeList[index].value;
            that.type = that.typeList[index].type;
        }else{
            console.log(that.useFromList[index].useFrom);
            // that.params.prescriptionType = that.useFromList[index].value;
            that.useFrom = that.useFromList[index].useFrom;
        }
        this.setData({
            'params.prescriptionState': that.params.prescriptionState,
            'params.prescriptionType': that.params.prescriptionType,
            state: that.state,
            type: that.type,
            useFrom: that.useFrom
        })
    },
    // 时间选择器
    bookTime(e) {
        let time = e.detail.time;
        let type = e.target.dataset.type;
        if (type === 'start') {
            that.params.startDate = time;
        } else {
            that.params.endDate = time;
        }
        this.setData({
            'params.startDate': that.params.startDate,
            'params.endDate': that.params.endDate
        })
    },
    tapactive(e) {
        console.log(e)
        var num = e.currentTarget.dataset.num;
        if (num == 0) {
            this.data.isshow = !this.data.isshow
            this.setData({
                isshow: this.data.isshow
            })
        } else {
            var index = e.currentTarget.dataset.index;
            this.setData({
                activenum: index
            })
        }

    },
    //一级选项卡
    taptitle(e) {
        var index = e.currentTarget.dataset.index;
        this.setData({
            istab: index
        })
        if (index == 1) {
            this.queryHistoryInterrogation();
        }
        if (index == 2) {
            this.getList();
        }
    },
    //二级选项卡
    taptab(e) {
        var index = e.currentTarget.dataset.index;
        name = [];
        this.setData({
            isactive: index,
            params: {
                "current": 1,
                "size": 10,
                "startDate": "",
                "endDate": "",
                "patientName": "",
                "patientPhone": "",
                "prescriptionState": "",
                "prescriptionType": "",
            },
            loadingText: '',
            loadingType: true
        })
        this.getList();
    },
    gotopage(e) {
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;
        var type = e.currentTarget.dataset.type;

        if (num == 0) { //处方用药详情 
            $service.openPage('../../../user_side/index/index_medication_details/index_medication_details?prescription_id=' + this.data.prescriptionlist[index].id + '&type=' + this.data.prescriptionlist[index].prescriptionType)
        } else if (num == 1) { //处方详情
            $service.openPage('../../../user_side/index/index_health_guidance/index_health_guidance?id=' + this.data.prescriptionlist[index].id + '&type=4')
        } else if (num == 2) { //检验检查详情
            $service.openPage('../../../user_side/index/index_health_guidance/index_health_guidance?id=' + this.data.checklistList[index].id + '&type=3')
        } else if (num == 3) { //健康指导
            $service.openPage('../../../user_side/index/index_health_guidance/index_health_guidance?id=' + this.data.guidanceList[index].id + '&type=2')
        } else if (num == 4) { //住院建议
            $service.openPage('../../../user_side/index/index_health_guidance/index_health_guidance?id=' + this.data.hospitalizationList[index].id + '&type=1')
        } else if (num == 5) { //查看患者信息
            let data = this.data.inquiryLogList[index]
            let url = $service.isHis ? `/pages/doctor_side/my_users/liangjiang-inquiry-history-list/liangjiang-inquiry-history-list?patientId=${data.patientId}&healthCardNo=${data.healthCardNo}&patientName=${data.patientName}` : `/pages/doctor_side/index/index_history/index_history?idCard=${data.patientIdcard}&name=${data.patientName}&logId=${data.logId}`
            $service.openPage(url)
        } else if (num == 6) { //处方作废
            delnum = num;
            this.data.isdeleteshow = true;
            id = this.data.prescriptionlist[index].prescription_id;
            this.data.name = $service.nothinglrsj(this.data.prescriptionlist[index].lrsj) + this.data.prescriptionlist[index].prescription_id + '处方'
        } else if (num == 7) { //检验检查作废
            delnum = num;
            this.data.isdeleteshow = true;
            id = this.data.checklistList[index].checklist_id;
            this.data.name = $service.nothinglrsj(this.data.checklistList[index].lrsj) + this.data.checklistList[index].checklist_id + '检验检查单'
        } else if (num == 8) { //健康指导作废
            delnum = num;
            this.data.isdeleteshow = true;
            id = this.data.guidanceList[index].id;
            this.data.name = this.data.guidanceList[index].patientName + '的健康指导单'
        } else if (num == 9) { //住院建议作废
            delnum = num;
            this.data.isdeleteshow = true;
            id = this.data.hospitalizationList[index].id;
            this.data.name = this.data.hospitalizationList[index].patientName + '的住院建议书'
        } else if (num == 10) { //确认作废
            if ($service.isUndefinedAndEmpty(this.data.reasons_invalidation)) {
                $service.showToast('请输入作废理由');
                return;
            }
            this.deletesheet()
        } else if (num == 11) { //取消作废
            this.data.isdeleteshow = false;
            this.data.reasons_invalidation = ''
        } else if (num == 12) { // 查看申请单
            console.log(this.data.applicationFormList[index]);
            $service.openPage('../../../user_side/index/index_health_guidance/index_health_guidance?id=' + this.data.applicationFormList[index].id + '&value=' + this.data.applicationFormList[index].templateValue + "&type=5")
        } else if (num == 13) {
            let {paymentMethod, id, storeId} = this.data.prescriptionlist[index]
            $service.openPage('/pages/doctor_side/index/index_edit_prescription/index?id=' + id + '&storeId=' + storeId + '&paymentMethod=' + paymentMethod)
        }
        this.setData({
            isdeleteshow: this.data.isdeleteshow,
            name: this.data.name,
            reasons_invalidation: this.data.reasons_invalidation
        })
    },
    //选择筛选类型
    tapzt(e) {
        console.log(e)
        var index = e.currentTarget.dataset.index;
        var num = e.currentTarget.dataset.num;

        if (index == 1) {
            this.data.isztshow = !this.data.isztshow
        } else if (index == 2) {
            console.log(num)
            if (num == 0) {
                this.data.zt = '已审核'
            } else if (num == 2) {
                this.data.zt = '未审核'
            } else if (num == 3) {
                this.data.zt = '全部'
            }
            this.data.isztshow = false
        } else if (index == 3) {
            this.data.isprescriptiontypeshow = !this.data.isprescriptiontypeshow
        } else if (index == 4) {
            if (num == 1) {
                this.data.prescription_type = '中药处方'
            } else if (num == 2) {
                this.data.prescription_type = '西药处方'
            } else if (num == 3) {
                this.data.prescription_type = '全部'
            }
            this.data.isprescriptiontypeshow = false
        }
        this.setData({
            isztshow: this.data.isztshow,
            zt: this.data.zt,
            isprescriptiontypeshow: this.data.isprescriptiontypeshow,
            prescription_type: this.data.prescription_type
        })
    },
    clearTime(e) {
        console.log(e)
        var index = e.currentTarget.dataset.index;
        if (index == 1) {
            this.data.startdate = '请选择开始时间';
            startTime = ''
        } else {
            this.data.enddate = '请选择结束时间'
            endTime = ''
        }
        this.setData({
            startdate: this.data.startdate,
            enddate: this.data.enddate
        })
    },
    //保存
    qr_Btn() {
        this.setData({
            isshow: false,
            'params.current': 1,
        })
        this.getList();
    },
    deletesheet() {
        let params = {
            "id": id,
            "reasonsInvalidation": this.data.reasons_invalidation
        }
        if (delnum == 8) { //指导意见
            app.http.deleteInquiryLogHealthGuidance(params).then(res => {
                $service.showToast(res.msg)
            }).catch(err => {
                $service.showToast(err.msg)
            })
        } else if (delnum == 9) { //住院建议
            app.http.revocationHospitalization(params).then(res => {
                $service.showToast(res.msg)
                this.getList();
            }).catch(err => {
                $service.showToast(err.msg)
            })
        }
        this.getList();
        this.setData({
            isdeleteshow: false,
            reasons_invalidation: ''
        })
    },
    /**
     * 上月切换
     */
    lastMonth: function () {
        //全部时间的月份都是按0~11基准，显示月份才+1
        let year = this.data.month - 2 < 0 ? this.data.year - 1 : this.data.year;
        let month = this.data.month - 2 < 0 ? 11 : this.data.month - 2;
        this.setData({
            year: year,
            month: (month + 1)
        })
        this.dateInit(year, month);
    },
    /**
     * 下月切换
     */
    nextMonth: function () {
        //全部时间的月份都是按0~11基准，显示月份才+1
        let year = this.data.month > 11 ? this.data.year + 1 : this.data.year;
        let month = this.data.month > 11 ? 0 : this.data.month;
        this.setData({
            year: year,
            month: (month + 1)
        })
        this.dateInit(year, month);
    },
    //获取日期
    getDay(type, time) {
        let now = new Date(time);
        if (type === 'day') {
            let day = '';
            switch (now.getDay()) {
                case 0:
                    day = "星期天";
                    break;
                case 1:
                    day = "星期一";
                    break;
                case 2:
                    day = "星期二";
                    break;
                case 3:
                    day = "星期三";
                    break;
                case 4:
                    day = "星期四";
                    break;
                case 5:
                    day = "星期五";
                    break;
                case 6:
                    day = "星期六";
            }
            return day
        } else {
            return now.getDate() + '号';
        }
    },
    viewQR(e) {
      let {item} = e.currentTarget.dataset
      if (item.loginMiniQrcodeurl) {
        wx.previewImage({
          urls: [item.loginMiniQrcodeurl],
        })
      } else {
        $service.showToast('未生成二维码')
      }
    }
});

function initChart(canvas, width, height) {
    const chart = echarts.init(canvas, null, {
        width: width,
        height: height
    });
    canvas.setChart(chart);

    //这里复制了官方示例配置
    var option = {
        color: ['#3398DB'],

        title: {
            text: '最近7天问诊记录',
            textStyle: {
                fontSize: 14
            }
        },
        tooltip: {
            // 当前鼠标位置
            position: function (point, params, dom, rect, size) {
                let x = point[0],
                    y = point[1],
                    viewWidth = size.viewSize[0],
                    boxWidth = size.contentSize[0],
                    posX = 0;
                if (x + boxWidth > viewWidth) {
                    posX = x - boxWidth;
                } else {
                    posX = x;
                }
                return [posX, y];
            },

        },
        legend: {
            data: ['问诊量']
        },
        xAxis: {
            data: timedata
        },
        yAxis: {},
        series: [{
            name: '日期/问诊数',
            type: 'bar',
            data: numdata
        }]
    };
    chart.setOption(option);
    return chart;
}